package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.*;
import com.web.exiaodao.business.repository.*;
import com.web.exiaodao.remote.service.ApiFavoriteTableService;
import com.web.exiaodao.remote.vo.FavoriteTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APIFavoriteTable接口实现类
 **/
@Service("ApiFavoriteTableService")
@Transactional(readOnly = false)
public class ApiFavoriteTableServiceImpl extends BaseService<FavoriteTable> implements ApiFavoriteTableService {

    private static final Logger LOGGER = Logger.getLogger(ApiFavoriteTableServiceImpl.class);

    @Autowired
    FavoriteTableRepository favoriteTableRepository;
    @Autowired
    ServiceCommonRepository serviceCommonRepository;
    @Autowired
    ServiceDomesticNursingRepository serviceDomesticNursingRepository;
    @Autowired
    ServiceNurseTrainingRepository nurseTrainingRepository;
    @Autowired
    VSDCRepository vsdcRepository;
    @Autowired
    InstitutionRepository institutionRepository;
    @Autowired
    InsHotelRoomsTableRepository insHotelRoomsTableRepository;
    @Autowired
    BannerRepository bannerRepository;
    @Autowired
    ShopRepository shopRepository;
    @Autowired
    ArtInformationRepository artInformationRepository;//作者
    @Autowired
    AutherWorksTableRepository autherWorksTableRepository;//作品
    @Autowired
    TravelTableRepository travelTableRepository;

    @Override
    public XaResult<FavoriteTableVo> findOne(Long tId) throws BusinessException {
        FavoriteTable obj = favoriteTableRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<FavoriteTableVo> xr = new XaResult<FavoriteTableVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FavoriteTableVo.class));
            xr.getObject().setId(obj.getId());
            LOGGER.info("查询单个实体----->FavoriteTable");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public XaResult<List<FavoriteTableVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<FavoriteTable> page = favoriteTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), FavoriteTable.class), pageable);
        XaResult<List<FavoriteTableVo>> xr = new XaResult<List<FavoriteTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), FavoriteTableVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<List<FavoriteTableVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<FavoriteTable> page = favoriteTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), FavoriteTable.class), pageable);
        XaResult<List<FavoriteTableVo>> xr = new XaResult<List<FavoriteTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), FavoriteTableVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<FavoriteTableVo> multiOperate(String modelIds,
                                                  Integer status) throws BusinessException {
        XaResult<FavoriteTableVo> xr = new XaResult<FavoriteTableVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                FavoriteTable obj = favoriteTableRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = favoriteTableRepository.save(obj);
                    xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FavoriteTableVo.class));
                    xr.getObject().setId(obj.getId());
                }
            }
        }
        LOGGER.info("更改数据状态----->FavoriteTable");
        return xr;
    }

    @Override
    public XaResult<FavoriteTableVo> createModel(FavoriteTable model)
            throws BusinessException {
        XaResult<FavoriteTableVo> xr = new XaResult<FavoriteTableVo>();

        FavoriteTable vo = favoriteTableRepository.findByUserIdAndFavoriteObjectIdAndTypeAndStatusNot(model.getUserId(), model.getFavoriteObjectId(), model.getType(), XaConstant.Status.delete);
        if (vo != null && vo.getFavoriteState()) {
            xr.error("已经收藏过,请不要重复收藏");
            return xr;
        }
        if (XaUtil.isNotEmpty(vo)) {
            model = vo;
        }
        model.setFavoriteState(true);

        //收藏
        int type = Integer.valueOf(model.getType());
        String favName = "";
        String favUrl = "";
        String subName = "";
        switch (type) {
            case JConstant.Search_Share_FavType.SERVICE: {
                ServiceCommon en = serviceCommonRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getTitle();
                favUrl = en.getImg();
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.SERVICE_DOMESITC_NURSING: {
                ServiceDomesticNursing en = serviceDomesticNursingRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getNurse_Name();
                favUrl = en.getNurse_PicUrl();
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.NURSE_TRANING: {
                ServiceNurseTraining en = nurseTrainingRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getNurseTraining_Name();
                favUrl = en.getNurseTraining_url();
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.NURSE_VSDC: {
                VSDC en = vsdcRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getVsdc_Name();
                favUrl = en.getVsdc_PicURL();
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.INSTIBUTION: {
                Institution en = institutionRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getInstitution_Name();
                favUrl = en.getInstitution_pic();
                subName = en.getInstitution_Site();//宣传语
            }
            break;
            case JConstant.Search_Share_FavType.HOURSE: {
                InsHotelRoomsTable en = insHotelRoomsTableRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getHotelRooms_Name();
                List<Banner> banner = bannerRepository.findByobjectIdAndTypeAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), JConstant.BannerType.INSTITUTION_HOURSE, XaConstant.Status.delete);
                if (XaUtil.isNotEmpty(banner)) {
                    favUrl = banner.get(0).getPicurl();
                }
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.GOODS: {
                Shop en = shopRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getShopProductName();
                if (XaUtil.isNotEmpty(en) && XaUtil.isNotEmpty(en.getShopProductPicUrls())) {
                    favUrl = en.getShopProductPicUrls().split(JConstant.SYMBOL_DOT)[0];
                }
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.ARTWORK: {
                AutherWorksTable en = autherWorksTableRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getWorksName();
                if (XaUtil.isNotEmpty(en.getWorksImgs())) {
                    favUrl = en.getWorksImgs().split(JConstant.SYMBOL_DOT)[0];
                }
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.ARTWORK_AUTHOR: {
                ArtInformation en = artInformationRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getAuthorName();
                favUrl = en.getAuthorIconPic();
                subName = "";
            }
            break;
            case JConstant.Search_Share_FavType.TOUR: {
                TravelTable en = travelTableRepository.findByIdAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), XaConstant.Status.delete);
                if (XaUtil.isEmpty(en)) {
                    xr.error("对象信息不存在(" + model.getFavoriteObjectId() + ")");
                    return xr;
                }
                favName = en.getTravelItemName();
                List<Banner> banners = bannerRepository.findByobjectIdAndTypeAndStatusNot(Long.valueOf(model.getFavoriteObjectId()), JConstant.BannerType.TRAVEL, XaConstant.Status.delete);
                if (XaUtil.isNotEmpty(banners)) {
                    favUrl = banners.get(0).getPicurl();
                }
                subName = en.getSlogan();//标语
            }
            break;
        }

        try {
            int lenght = ReflectionUtils.getHibernateColumnAnnotationLength(FavoriteTable.class, "favName");
            model.setFavName(XaUtil.getSubStr(favName, lenght));

            lenght = ReflectionUtils.getHibernateColumnAnnotationLength(FavoriteTable.class, "favUrl");
            model.setFavUrl(XaUtil.getSubStr(favUrl, lenght));

            lenght = ReflectionUtils.getHibernateColumnAnnotationLength(FavoriteTable.class, "subName");
            model.setSubName(XaUtil.getSubStr(subName, lenght));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getLocalizedMessage());
        }

        FavoriteTable obj = favoriteTableRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FavoriteTableVo.class));
        xr.getObject().setId(obj.getId());

        LOGGER.info("新增数据成功----->FavoriteTable");
        return xr;
    }

    @Override
    public XaResult<FavoriteTableVo> updateModel(FavoriteTable model)
            throws BusinessException {
        FavoriteTable obj = favoriteTableRepository.findOne(model.getId());
        XaResult<FavoriteTableVo> xr = new XaResult<FavoriteTableVo>();
        if (XaUtil.isNotEmpty(obj)) {
            obj.setFavoriteObjectId(XaUtil.isNotEmpty(model.getFavoriteObjectId()) ? model.getFavoriteObjectId() : obj.getFavoriteObjectId());
            obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
            obj.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : obj.getType());
            obj.setFavoriteState(XaUtil.isNotEmpty(model.getFavoriteState()) ? model.getFavoriteState() : obj.getFavoriteState());
            obj = favoriteTableRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FavoriteTableVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error(XaConstant.Message.object_not_find);
        }
        LOGGER.info("编辑数据成功----->FavoriteTable");
        return xr;
    }

    @Override
    public XaResult<FavoriteTable> isFavorite(Long userId, Long favoriteObjectId, String type) throws BusinessException {
        XaResult<FavoriteTable> xr = new XaResult<>();
        FavoriteTable vo = favoriteTableRepository.findByUserIdAndFavoriteObjectIdAndTypeAndStatusNot(userId, favoriteObjectId.toString(), type, XaConstant.Status.delete);
        if (vo != null) {
            xr.setObject(vo);
            return xr;
        }
        xr.setObject(null);
        return xr;
    }
}
